<?php
//echo ini_get('post_max_size');
//echo ini_get('upload_max_filesize');



$type = $_GET['type'];

error_reporting(0);
session_start();
error_reporting(1);

require_once "../common/PinSQL.obj";
$pinSQL = new PinSQL();

$username = $_SESSION['username'];
	
$name = $_POST['name'];
$name_safe = addslashes($name);

if ($name == "__userpic__")
{
	$target_path = "userData/$username/";
} else {
	$target_path = "userData/$username/$type/";
}


if ($type == "blog")
{
	$description = $_POST['caption'];
	$description_safe = addslashes($description);
	
	$pinSQL->Query("INSERT INTO blogdata
		(name, description, artist)
		VALUES ('$name_safe', '$description_safe', '$username')");
		
	$shorttype = "entry";
	$dataTable = "blogdata";
	
	$result = mysql_query("SELECT * FROM blogdata WHERE name='$name_safe'") or die(mysql_error());
	$id = mysql_result($result, 0, "id");

	if ($pinSQL->GetPrivacyField($_SESSION['id'], "postblog") == 1)
	{
		mysql_query("INSERT INTO activity
		(event_type, by_user, param_1, param_long, url_1)
		VALUES('new-$shorttype', '$username', '$id', '$description_safe',
		'/members/frame.php?page=profile&tab=blog&user=$username') ")
		or die(mysql_error());
	}
	
	header ("Location: frame.php?page=profile&tab=blog&user=$username");
	exit;
	
}

$filename = basename( $_FILES['file']['name'] );
$target_path = $target_path . $filename; 
$filename_safe = addslashes($filename);


if(@move_uploaded_file($_FILES['file']['tmp_name'], $target_path))
{
	
	
	if ($type == "pictures")
	{
		// *** resize the image for thumbnail and server storage ***
		$filenameSplit = explode(".", $filename);
		$fileTitle = $filenameSplit[0];
		$fileTitle_safe = addslashes($fileTitle);
		$fileExt = $filenameSplit[1];
		$fileDirectory = dirname($target_path);
		
		$oldDimensions = getimagesize($target_path);
		$oldWidth = $oldDimensions[0];
		$oldHeight = $oldDimensions[1];
		
		// --- (1) create thumbnail ---
		
		// calculate aspect ratio of original
		if ($oldWidth <= 200)
		{
			// if the original is smaller then 200 pixels (horizontal), keep the original size.
			$newWidth = $oldWidth;
			$newHeight = $oldHeight;
		} else {
			$heightFactor = $oldHeight / $oldWidth;
			$newWidth = 200;
			$newHeight = $newWidth * $heightFactor;
		}
		
		// create image buffers
		if ( preg_match('/jpg|jpeg|JPG|JPEG/', $filename) )
		{
			$srcImg = imagecreatefromjpeg($target_path);
		}
		elseif ( preg_match('/png|PNG/', $filename) )
		{
			$srcImg = imagecreatefrompng($target_path);
		}
		elseif ( preg_match('/gif|GIF/', $filename) )
		{
			$srcImg = imagecreatefromgif($target_path);
		}
		else
		{
			echo "Sorry, but the '$fileExt' image format is not supported.";
			unlink($target_path); // delete original
			exit;
			
		}
		
		$destImg = imagecreatetruecolor($newWidth, $newHeight);
		
		// blit resized image into destination image buffer
		imagecopyresampled($destImg, $srcImg, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight); 
	
		// save resulting thumbnail as JPEG
		error_reporting(0);
		unlink($fileDirectory . "/" . $fileTitle . "-thumb.jpg");
		error_reporting(1);
		imagejpeg($destImg, $fileDirectory . "/" . $fileTitle . "-thumb.jpg");
		
		// destroy thumbnail
		imagedestroy($dst_img);
		
		// --- (2) create new server-friendly original image (800x??? pixels) ---
		// Note: this is to guard against hideously large digital camera pictures with resolutions like 3108x2154 and sizes of 2-3MB.
		
		// calculate aspect ratio of original
		if ($oldWidth <= 800)
		{
			// if the original is smaller then 200 pixels (horizontal), keep the original size.
			$newWidth = $oldWidth;
			$newHeight = $oldHeight;
		} else {
			$heightFactor = $oldHeight / $oldWidth;
			$newWidth = 800;
			$newHeight = $newWidth * $heightFactor;
		}
		
		// create image buffers
		$destImg = imagecreatetruecolor($newWidth, $newHeight);
		
		// blit resized image into destination image buffer
		imagecopyresampled($destImg, $srcImg, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight); 
	
		// save resulting thumbnail as JPEG
		error_reporting(0);
		unlink($fileDirectory . "/" . $fileTitle . "-main.jpg");
		error_reporting(1);
		imagejpeg($destImg, $fileDirectory . "/" . $fileTitle . "-main.jpg");
		
		// destroy thumbnail
		imagedestroy($dst_img);
	
		// --- done with source image ---
		imagedestroy($src_img);
		unlink($target_path); // delete original
	}//picture resizing
	
	//only apply post-image bookkeeping to non-profile images
	if ($name != "__userpic__")
	{
		$caption = $_POST['caption'];
		$caption_safe = addslashes($caption);
		$displayActivity = 0;
		
		
		echo "INSERT INTO picturedata
					(name, description, filename, thumburl, artist)
					VALUES ('$name_safe', '$caption_safe', '$fileTitle_safe-main.jpg', '$fileTitle_safe-thumb.jpg', '$username')";
		
		switch ($type)
		{
			case 'pictures':
				$pinSQL->Query("INSERT INTO picturedata
					(name, description, filename, thumburl, artist)
					VALUES ('$name_safe', '$caption_safe', '$fileTitle_safe-main.jpg', '$fileTitle_safe-thumb.jpg', '$username')");
					
				$shorttype = "picture";
				$dataTable = "picturedata";
				
				$displayActivity = $pinSQL->GetPrivacyField($_SESSION['id'], "postpicture");
				echo $displayActivity;
				break;
				
			case 'music':
				$caption = $_POST['caption'];
				$pinSQL->Query("INSERT INTO songdata
					(name, description, artist, filename)
					VALUES ('$name_safe', '$caption_safe', '$username', '$filename_safe')");
					
				$shorttype = "song";
				$dataTable = "songdata";
				
				$displayActivity = $pinSQL->GetPrivacyField($_SESSION['id'], "postsong");
				break;
		}
		
		$result = mysql_query("SELECT * FROM " . $shorttype . "data WHERE name='$name_safe'") or die(mysql_error());
		$id = mysql_result($result, 0, "id");

		if ($displayActivity == 1)
		{
			mysql_query("INSERT INTO activity
			(event_type, by_user, param_1, param_long, url_1)
			VALUES('new-$shorttype', '$username', '$id', '$caption_safe',
			'/common/gallery/portal_$type.php?dest=$id') ")
			or die(mysql_error());
		}
		
		header ("Location: frame.php?page=myuploads");
	} else {
		$pinSQL->Query("SELECT * FROM members WHERE username='$username'");
		$row = $pinSQL->FetchNextRow();
		$id = $row['id']; // gets ID of currently viewed user
		
		$pinSQL->Query("UPDATE memberdata SET picurl='$fileTitle_safe-thumb.jpg' WHERE id='$id'");
		
		if ($pinSQL->GetPrivacyField($_SESSION['id'], "profilechange") == 1)
		{
			mysql_query("INSERT INTO activity
			(event_type, by_user, url_1)
			VALUES('profile-newpic', '$username',
			'/members/frame.php?page=profile&user=$username') ")
			or die(mysql_error());
		}
		
		header ("Location: frame.php?page=profile&user=$username");
	}
	
	
    
} else {
    echo "There was an error uploading the file, please try again!";
    echo "<br>".$_FILES['file']['error'];
}

?>